﻿using MediatR;
using SqlSugar;
using Warehouse.Domain;
using Warehouse.ErrorCord;
using Warehouse.Read.Api.Actions.Command.WarehouseCategory;
using Warehouse.Read.Api.DTO;

namespace Warehouse.Read.Api.Actions.CommandHandel.WarehouseCategory
{
    public class GetShowWareCommandHandle : IRequestHandler<GetShowWareCommand, APIResult<APIPaging<WarehouseDTO>>>
    {
        private readonly ISqlSugarClient db;

        public GetShowWareCommandHandle(ISqlSugarClient db)
        {
            this.db = db;
        }
        public Task<APIResult<APIPaging<WarehouseDTO>>> Handle(GetShowWareCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<WarehouseDTO>> result = new APIResult<APIPaging<WarehouseDTO>>();
            var list = db.Queryable<Warehouse.Domain.WarehouseInformation>()
                .InnerJoin<Warehouse.Domain.WarehouseCategory>((a,b)=>a.WarehouseTypeId==b.WarehouseTypeId)
                .Where((a,b)=>a.IsDel==false&&b.IsDel==false)
               
                .Select((a,b)=>new WarehouseDTO 
                {
                    WarehouseId=a.WarehouseId,
                    MyPropertylogid=a.MyPropertylogid,
                    WarehouseName=a.WarehouseName,
                    WarehouseTypeId=b.WarehouseTypeId,
                    WarehouseTypeName=b.WarehouseTypeName,
                    WarehouseAdder=a.WarehouseAdder,
                    WarehouseRemark=a.WarehouseRemark,
                    CreateTime=a.CreateTime,
                    IsDel=a.IsDel,
                });

            if (request.WarehouseTypeId != 0)
            {
                list = list.Where(a => a.WarehouseTypeId == request.WarehouseTypeId);
            }
            if (!string.IsNullOrEmpty(request.WarehouseName))
            {
                list = list.Where(a => a.WarehouseName.Contains(request.WarehouseName));
            }
            if (!string.IsNullOrEmpty(request.MyPropertylogid))
            {
                list = list.Where(a => a.MyPropertylogid == request.MyPropertylogid);
            }

            APIPaging<WarehouseDTO> page = new APIPaging<WarehouseDTO>();
            page.TotalCount = list.Count();
            page.PageCount = Math.Ceiling(list.Count() * 1.0 / request.PageSize);
            page.list = list.OrderByDescending(a => a.WarehouseId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Code = APIEnum.Success;
            result.Msg = "查询成功";
            result.Data = page;
            return Task.FromResult(result);
        }
    }
}
